<template>
  <div class="cs-p">
    <el-form
      :inline="true"
      size="small">

      <el-form-item v-if="auth.add">
        <el-button
          v-if="isAuth('sys:member:save')"
          icon="el-icon-plus"
          :disabled="loading"
          @click="handleCreate">新增用户</el-button>
      </el-form-item>

      <el-form-item v-if="auth.enable || auth.disable">
        <el-button-group>
          <el-button
            v-if="auth.enable"
            icon="el-icon-check"
            :disabled="loading"
            @click="handleState(1)">启用</el-button>

          <el-button
            v-if="auth.disable"
            icon="el-icon-close"
            :disabled="loading"
            @click="handleState(0)">禁用</el-button>
        </el-button-group>
      </el-form-item>

      <el-form-item v-if="auth.del">
        <el-button
          icon="el-icon-delete"
          :disabled="loading"
          @click="handleDelete(multipleSelection)">删除</el-button>
      </el-form-item>

      <!-- <cs-help
        :router="$route.path"
        style="padding-bottom: 19px;">
      </cs-help> -->
    </el-form>

    <cs-table :table-data="currentTableData"
              :table-label="tableLabel"
              @handleButton="handleButton"
              @handleSortChange="handleSortChange"
              @handleSelectionChange="handleSelectionChange"
              :table-option="tableOption">
      <template slot="status" slot-scope="scope">
        <el-tag v-if="scope.row.status==='0'">启用</el-tag>
        <el-tag v-if="scope.row.status==='1'" type="danger">禁用</el-tag>
      </template>
    </cs-table>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="600px">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="80px">
        <el-form-item
          label="账号"
          prop="account">
          <el-input
            v-model="form.account"
            :disabled="dialogStatus !== 'create'"
            placeholder="请输入账号"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          v-if="dialogStatus === 'create'"
          label="密码"
          prop="password">
          <el-input
            type="password"
            v-model="form.password"
            placeholder="请输入密码"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          v-if="dialogStatus === 'create'"
          label="确认密码"
          prop="password_confirm">
          <el-input
            type="password"
            v-model="form.password_confirm"
            placeholder="请再次输入密码"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          label="昵称"
          prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入昵称"
            :clearable="true"/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item
              label="性别"
              prop="sex">
              <el-select
                v-model="form.sex"
                placeholder="请选择"
                value="">
                <el-option
                  v-for="item in sexOption"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item
              label="生日"
              prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          label="手机号"
          prop="phone">
          <el-input
            type='number'
            v-model="form.phone"
            placeholder="请输入手机号"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          label="邮箱"
          prop="email">
          <el-input
            type="email"
            v-model="form.email"
            placeholder="请输入邮箱"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          label="用户组"
          prop="roleIds">
          <el-select
            v-model="form.roleIds"
            multiple
            placeholder="请选择"
            style="width: 100%;"
            value="">
            <el-option
              v-for="item in group"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"/>
          </el-select>
        </el-form-item>

        <el-form-item
          label="状态"
          prop="status">
          <el-switch
            v-model="form.status"
            active-value="0"
            inactive-value="1">
          </el-switch>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          @click="dialogFormVisible = false"
          size="small">取消</el-button>

        <el-button
          v-if="dialogStatus === 'create'"
          type="primary"
          :loading="dialogLoading"
          @click="create"
          size="small">确定</el-button>

        <el-button
          v-else type="primary"
          :loading="dialogLoading"
          @click="update(form.index)"
          size="small">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  setAdminStatus,
  delAdminList,
  addAdminItem,
  setAdminItem,
  resetAdminItem
} from '@/api/user/admin'
import util from '@/utils/util'

export default {
  components: {
    'CsTable': () => import('@/components/cs-table')
  },
  props: {
    tableData: {
      default: () => []
    },
    loading: {
      default: false
    },
    group: {
      default: () => []
    }
  },
  data() {
    let validateConfirmPassword = (rule, value, callback) => {
      if (this.form.password !== value) {
        callback(new Error('确认密码与新密码不一致'))
      } else {
        callback()
      }
    }
    return {
      tableLabel: [
        { label: '账号', param: 'account', align: 'center', sortable: false, isShow: true },
        { label: '昵称', param: 'name', align: 'center', isShow: true },
        { label: '角色', param: 'roleNames', align: 'center', sortable: false, isShow: true },
        { label: '性别',
          param: 'sex',
          align: 'center',
          sortable: false,
          render: (row) => {
            if (row.sex === '1') {
              return '男'
            } else if (row.sex === '2') {
              return '女'
            } else {
              return '未知'
            }
          }
        },
        { label: '邮箱', param: 'email', align: 'center', sortable: false, isShow: true },
        { label: '电话', param: 'phone', align: 'center', sortable: false, isShow: true },
        { label: '状态', param: 'status', align: 'center', sortable: false, slot: true, isShow: true },
        { label: '创建时间',
          param: 'createTime',
          align: 'center',
          sortable: false,
          render: (row) => {
            return util.formatTimeToStr(row.createTime, 'yyyy-MM-dd')
          }
        }
      ],
      tableOption: {
        label: '操作',
        width: '200',
        options: [
          { label: '编辑', type: 'primary', icon: 'el-icon-edit', methods: 'audit', auth: 'sys:member:update' },
          { label: '删除', type: 'danger', icon: 'el-icon-delete', methods: 'delete', auth: 'sys:member:delete' }
        ]
      },
      currentTableData: [],
      multipleSelection: [],
      auth: {
        add: true,
        del: true,
        set: true,
        enable: false,
        disable: false,
        reset: true
      },
      dialogLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '新增用户'
      },
      sexOption: [
        { name: '男', value: '1' },
        { name: '女', value: '2' }
      ],
      form: {
        userId: undefined,
        account: undefined,
        name: undefined,
        password: undefined,
        password_confirm: undefined,
        roleIds: [],
        birthday: '',
        email: undefined,
        phone: undefined,
        sex: undefined,
        status: '0'
      },
      rules: {
        account: [
          {
            required: true,
            message: '账号不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 20,
            message: '长度在 4 到 20 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          {
            min: 6,
            message: '长度不能少于 6 个字符',
            trigger: 'blur'
          }
        ],
        password_confirm: [
          {
            required: true,
            message: '确认密码不能为空',
            trigger: 'blur'
          },
          { validator: validateConfirmPassword, trigger: 'change' }
        ],
        name: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: 'blur'
          },
          {
            max: 50,
            message: '长度不能大于 50 个字符',
            trigger: 'blur'
          }
        ],
        roleIds: [
          {
            required: true,
            message: '至少选择一项',
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    tableData: {
      handler(val) {
        this.currentTableData = val
      },
      immediate: true
    }
  },
  mounted() {
    this._validationAuth()
  },
  methods: {
    // 验证权限
    _validationAuth() {
      this.auth.add = this.$permission('/system/admin/member/add')
      this.auth.del = this.$permission('/system/admin/member/del')
      this.auth.set = this.$permission('/system/admin/member/set')
      this.auth.enable = this.$permission('/system/admin/member/enable')
      this.auth.disable = this.$permission('/system/admin/member/disable')
      this.auth.reset = this.$permission('/system/admin/member/reset')
    },
    handleButton(methods, row, index) {
      // 修改
      if (methods.methods === 'audit') {
        this.handleUpdate(methods.index)
      } else if (methods.methods === 'delete') { // 删除
        this.handleDelete(methods.index)
      }
    },
    // 排序
    handleSortChange(val) {
      console.log(val)
    },
    // 获取列表中的用户编号
    _getClientIdList(val) {
      let clients = []
      if (Array.isArray(val)) {
        val.forEach(value => {
          clients.push(value.userId)
        })
      } else {
        clients.push(this.currentTableData[val].userId)
      }

      return clients
    },
    // 选中数据项
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取排序字段
    sortChange({ column, prop, order }) {
      let sort = {
        order_type: undefined,
        order_field: undefined
      }

      if (column && order) {
        sort.order_type = order === 'ascending' ? 'asc' : 'desc'
        sort.order_field = prop
      }

      this.$emit('sort', sort)
    },
    // 批量设置状态
    handleState(state) {
      let clients = this._getClientIdList(this.multipleSelection)
      if (clients.length === 0) {
        this.$message.error('请选择要操作的数据')
        return
      }

      this.$confirm('确定要执行该操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(() => {
          setAdminStatus(clients, state)
            .then(() => {
              this.currentTableData.forEach((value, index) => {
                if (clients.indexOf(value.admin_id) !== -1) {
                  // value.status = enable // 此修改可保持勾选状态
                  this.$set(this.currentTableData, index, {
                    ...value,
                    status: state
                  })
                }
              })

              this.$message.success('操作成功')
            })
        })
        .catch(() => {
        })
    },
    // 批量删除
    handleDelete(val) {
      let clients = this._getClientIdList(val)
      if (clients.length === 0) {
        this.$message.error('请选择要操作的数据')
        return
      }
      this.$confirm('确定要执行该操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(() => {
          delAdminList(clients[0])
            .then(() => {
              for (let i = this.currentTableData.length - 1; i >= 0; i--) {
                if (clients.indexOf(this.currentTableData[i].userId) !== -1) {
                  this.currentTableData.splice(i, 1)
                }
              }
              this.$emit('refresh', true)
            })
        })
        .catch(() => {
        })
    },
    // 弹出新建对话框
    handleCreate() {
      this.form = {
        account: undefined,
        password: undefined,
        password_confirm: undefined,
        roleIds: [],
        name: undefined,
        sex: '1',
        birthday: '',
        phone: '',
        email: '',
        status: '0'
      }

      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }

        this.dialogStatus = 'create'
        this.dialogLoading = false
        this.dialogFormVisible = true
      })
    },
    // 请求新建用户
    create() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          this.form.roleIds = this.form.roleIds.toString()
          addAdminItem({ ...this.form })
            .then(res => {
              // this.currentTableData.unshift({
              //   ...res.data,
              //   status: 1,
              //   get_auth_group: {
              //     ...this.group.find(item => item.group_id === res.data.group_id)
              //   }
              // })
              this.$emit('refresh')
              this.dialogFormVisible = false
              // this.$message.success('操作成功')
            })
            .catch(() => {
              this.dialogLoading = false
            })
        }
      })
    },
    // 弹出编辑对话框
    handleUpdate(index) {
      this.form = { ...this.currentTableData[index] }
      this.form.roleIds = this.form.roleIds ? this.form.roleIds.split(',') : []
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }

        this.dialogStatus = 'update'
        this.dialogLoading = false
        this.dialogFormVisible = true
      })
    },
    // 请求修改用户
    update(index) {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          this.form.roleIds = this.form.roleIds.toString()
          setAdminItem({ ...this.form })
            .then(res => {
              this.$emit('refresh')
              this.dialogFormVisible = false
            })
            .catch(() => {
              this.dialogLoading = false
            })
        }
      })
    },
    // 重置密码
    reset(index) {
      const admin = this.currentTableData[index]
      this.$confirm(`确定要重置 ${admin.username} 的密码吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(() => {
          resetAdminItem(admin.admin_id)
            .then(res => {
              this.$notify({
                title: '重置密码',
                dangerouslyUseHTMLString: true,
                message: `${admin.username} 的密码已重置为：</br>${res.data.password}`,
                type: 'success',
                position: 'bottom-right',
                duration: 0
              })
            })
        })
        .catch(() => {
        })
    },
    // 切换状态
    switchStatus(index) {
      let oldData = this.currentTableData[index]
      const newStatus = oldData.status ? 0 : 1

      if (oldData.status > 1) {
        return
      }

      // 禁用权限检测
      if (newStatus === 0 && !this.auth.disable) {
        return
      }

      // 启用权限检测
      if (newStatus === 1 && !this.auth.enable) {
        return
      }

      this.$set(this.currentTableData, index, { ...oldData, status: 2 })
      setAdminStatus([oldData.admin_id], newStatus)
        .then(() => {
          this.$message.success('操作成功')
          this.$set(this.currentTableData, index, {
            ...oldData,
            status: newStatus
          })
        })
        .catch(() => {
          this.$set(this.currentTableData, index, oldData)
        })
    }
  }
}
</script>
